using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Config;
using net_work.Data.DTO.Hmw;
using net_work.Data.Entity.Hmw;
using net_work.Data.VO.Hmw;
using net_work.IRepository.Hmw;

namespace net_work.Repository.Hmw;

public class BankQuestionRepository(ApplicationDbContext dbContext)
    : Repository<BankQuestion>(dbContext), IBankQuestionRepository
{
    public async Task<long> InsertAsync(BankQuestionAddRequest bankQuestionAddRequest)
    {
        var newBankQuestion = new BankQuestion
        {
            Remark = bankQuestionAddRequest.Remark,
            Title = bankQuestionAddRequest.Title,
            Content = bankQuestionAddRequest.Content,
            Type = bankQuestionAddRequest.Type,
            Score = bankQuestionAddRequest.Score,
            CourseId = bankQuestionAddRequest.CourseId
        };
        await dbContext.BankQuestions.AddAsync(newBankQuestion);
        await dbContext.SaveChangesAsync();
        return newBankQuestion.Id;
    }

    public async Task<bool> UpdateAsync(BankQuestionUpdateRequest bankQuestionUpdateRequest)
    {
        var bankQuestion = await dbContext.BankQuestions.FindAsync(bankQuestionUpdateRequest.Id);
        if (bankQuestion == null)
        {
            return false;
        }

        bankQuestion.Remark = bankQuestionUpdateRequest.Remark;
        bankQuestion.Title = bankQuestionUpdateRequest.Title;
        bankQuestion.Content = bankQuestionUpdateRequest.Content;
        bankQuestion.Type = bankQuestionUpdateRequest.Type;
        bankQuestion.Score = bankQuestionUpdateRequest.Score;
        bankQuestion.CourseId = bankQuestionUpdateRequest.CourseId;

        await dbContext.SaveChangesAsync();
        return true;
    }

    public Task<PagedResult<BankQuestionResult>> GetBankQuestionPagedAsync(PagedRequest request)
    {
        var query = from bankQuestion in dbContext.BankQuestions
            join course in dbContext.Courses on bankQuestion.CourseId equals course.Id
            select new BankQuestionResult
            {
                Id = bankQuestion.Id,
                Title = bankQuestion.Title,
                Content = bankQuestion.Content,
                Type = bankQuestion.Type,
                Score = bankQuestion.Score,
                CourseId = bankQuestion.CourseId,
                CourseName = course.CouName,
                Remark = bankQuestion.Remark,
                CreatedTime = bankQuestion.CreatedTime,
                CreatedBy = bankQuestion.CreatedBy,
                UpdatedTime = bankQuestion.UpdatedTime,
                UpdatedBy = bankQuestion.UpdatedBy,
                DelFlag = bankQuestion.DelFlag
            };

        return GetPagedQueryResultAsync(query, request);
    }
}